package com.yunhe.authority.repository.authority.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yunhe.authority.domain.authority.BackUser;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.StringUtil;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author zhengbo
 * @date 2021/10/22 11:06
 */
@Repository
public class BackUserDao {

    @Autowired
    private Session session;

    public Page<BackUser> findUsersById(Long id,
                                        String keywords,
                                        PageParam pageParam) {
        StringBuffer cql = new StringBuffer();
        //拼接基本语句
        cql.append("MATCH(u:BackUser)-[:HAS_ROLE]->(r:Role) WHERE ID(r) = " + id + " ");
        if (!StringUtil.isEmpty(keywords)) {
            cql.append(" AND (u.name=~'.*" + keywords + ".*' ");
            cql.append(" or u.title=~'.*" + keywords + ".*' ");
            cql.append(" or u.ascriptionOrgTitle=~'.*" + keywords + ".*') ");
        }

        //拼接返回值和Limit部分
        int skip = (pageParam.getPage() - 1) * pageParam.getSize();
        String queryEnd = " RETURN u order by u.createTime desc SKIP " + skip + " LIMIT " + pageParam.getSize();
        String countEnd = " RETURN count(u) ";


        //分页数据查询结果
        Iterable<BackUser> users = session.query(BackUser.class, cql.toString() + queryEnd, Maps.newHashMap());
        //查询总数
        Integer total = session.queryForObject(Integer.class, cql.toString() + countEnd, Maps.newHashMap());

        //封装为分页类
        List<BackUser> content = Lists.newArrayList(users);
        Pageable pageable = PageRequest.of(pageParam.getPage() - 1, pageParam.getSize());
        Page<BackUser> page = new PageImpl<BackUser>(content, pageable, total);
        return page;
    }
}
